(function () {
    function workFlow(time) {
        this.index = 0;
        this.count = 0;
        this.fnlist = [];
        this.isAuto = false;
        this.isLoop = false;
        this.isRun = false;
        this.time = time || 0;
    }
    workFlow.prototype.add = function (fn, time, arg) {
        this.fnlist.push({
            fn: fn,
            time: time || this.time,
            arg: arg
        });
        this.count++;
        return this;
    }
    workFlow.prototype.remove = function (order) {
        if (this.count > 0 && order < this.count && order > 0) {
            this.fnlist.forEach(function (obj, i, arr) {
                if (i == order) {
                    arr.splice(i, 1);
                }
            });
            this.count--;
            this.index = this.index > 0 ? this.index - 1 : 0;
        }
        return this;
    }
    workFlow.prototype.clear = function () {
        this.index = 0;
        this.count = 0;
        this.fnlist = [];
        return this;
    }
    workFlow.prototype.next = function (arg) {
        if (this.isRun) return;
        if (this.index < this.count) {
            var item = this.getItem();
            this.run(item.fn, item.time, arg || item.arg);
            this.index++;
            if (this.index == this.count) {
                if (this.isLoop) {
                    this.index = 0;
                }
            }
        } else {
            console.log("已执行完毕，可reset重置");
        }
        return this;
    }
    workFlow.prototype.run = function (fn, time, arg) {
        var self = this;
        self.isRun = true;
        setTimeout(function () {
            fn(arg);
            self.isRun = false;
            if (self.isAuto) {
                self.next();
            }
        }, time);
    }
    workFlow.prototype.reset = function () {
        this.index = 0;
    }
    workFlow.prototype.start = function () {
        var args = [].slice.call(arguments);
        if (args.length > 0) {
            var count = this.count;
            var fnlist = this.fnlist;
            args.forEach(function (arg, i) {
                if (i < count) {
                    fnlist[i].arg = arg;
                }
            });
            this.fnlist = fnlist;
        }
        this.isAuto = true;
        this.next();
    }
    workFlow.prototype.getItem = function () {
        var index = this.index;
        return this.fnlist.slice(index, index + 1)[0];
    }
    window.workFlow = workFlow;
})();